﻿#region Copyright and License
/*==============================================================================
 *  Copyright (c) www.51mvc.com Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.51mvc.com/
 * Create By 小鱼(Leven)  - http://leven.com.cn
 * ==============================================================================*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Infancy.Core.Validation {
    /// <summary>
    /// 正则验证特性
    /// </summar>
    [AttributeUsage(AttributeTargets.Property)]
    public class RegexValidateAttribute : NullableValidateAttribute {
        /// <summary>
        /// 用于验证的表达式
        /// </summary>
        public string Pattern { get; private set; }

        public RegexValidateAttribute(string pattern, bool cannull)
            : base(cannull) {
            Pattern = pattern;
            Message = "验证错误";
        }

        public RegexValidateAttribute(string pattern)
            : this(pattern, false) {
        }

        #region IValidateFilter Members

        public override ValidatedResult Execute(ValidateContext context) {
            ValidatedResult baseResult = base.Execute(context);
            if (!baseResult.Result) {
                return baseResult;
            } else if (CanNull && 
                (context.Value is String ? 
                    String.IsNullOrEmpty(context.Value as String) : context.Value == null)) {
                return baseResult;
            } else {
                ValidatedResult result = new ValidatedResult(
                    Regex.IsMatch(Convert.ToString(context.Value), Pattern));
                if (!result.Result) {
                    result.Errors.Add(context.Name, Message);
                }
                return result;
            }
        }

        #endregion
    }
}
